package team.xiaobaiya.gptchatrobot.gpt;

import com.squareup.okhttp.*;
import lombok.extern.slf4j.Slf4j;
import okio.ForwardingSink;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import team.xiaobaiya.gptchatrobot.exception.ChatException;
import team.xiaobaiya.gptchatrobot.exception.SystemException;
import team.xiaobaiya.gptchatrobot.gpt.request.ChatRequestBody;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName GptClient
 * @Author Feng Yingnan
 * @Email fengyn1211@163.com
 * @Date 2023/4/6 15:23
 */
@Slf4j
@Component
public class GptClient {
    private final String COMPLETION_ENDPOINT = "https://api.openai.com/v1/chat/completions";

    @Value("${gpt.api-key}")
    private String apiKey;
    @Value("${network.proxy-host}")
    private String proxyHost;
    @Value("${network.proxy-port}")
    private int proxyPort;

    OkHttpClient client = new OkHttpClient();
    MediaType mediaType;
    Request.Builder requestBuilder;
    @PostConstruct
    private void init() {
        client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
        client.setConnectTimeout(60, TimeUnit.SECONDS);
        client.setReadTimeout(60, TimeUnit.SECONDS);
        mediaType = MediaType.parse("application/json; charset=utf-8");
        requestBuilder = new Request.Builder()
                .url(COMPLETION_ENDPOINT)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey);
    }


    /**
     * 聊天接口
     * @param requestBody 聊天接口请求体
     * @return 接口请求响应
     */
    public Response chat(ChatRequestBody requestBody) throws ChatException {
        RequestBody bodyOk = RequestBody.create(mediaType, requestBody.toString());
        Request requestOk = requestBuilder.post(bodyOk).build();

        Call call = client.newCall(requestOk);
        Response response;
        try {
            response = call.execute();
        } catch (IOException e) {
            throw new ChatException("请求时IO异常: " + e.getMessage());
        }
        if (response.isSuccessful()) {
            return response;
        }
        try(ResponseBody body = response.body()) {
            throw new ChatException("chat api 请求异常, code: " + response.code() + "body: " + body.string());
        } catch (IOException e) {
            throw new ChatException("请求后IO异常: " + e.getMessage());
        }
    }

}
